//
//  XGL_LiveRoomViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/30.
//

import UIKit

class XGL_LiveRoomViewController: UIViewController,CustomNavgationBar {
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var liveCoverView: UIImageView!
    var inforView: XGL_LiveRoomUserItemView!
    var chatView: XGL_LiveRoomChatView!
    var chatInputView: XGL_LiveRoomChatInputView!
    lazy var giftPickerView = XGL_GiftListBarView()
    lazy var animationView = XGL_GiftAnimationView()
    var liveData: PublishData?
    var liveId: String = ""
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "")
       
        if let data = self.liveData {
            if let imageUrl = data.data3{
                self.liveCoverView.loadImageWithUrl(imageUrl)
            }
            if let infor = data.auditUserExt {
                self.inforView.userHeadView.userData = infor
                self.inforView.userNameText.text = infor.data1
            }else{
                if let userId = self.liveData?.userId {
                    self.inforView.userId = userId.description
                    self.inforView.userHeadView.userId = userId.description
                }
                self.getUserDataRequest()
            }
        }
        self.getCommentDatasRequest()
        self.getIsFollowRequest()
        self.getGiftDatasRequest()
    }

}

extension XGL_LiveRoomViewController{
    @objc private func moreItemAction(){
        let actionController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let action = UIAlertAction(title: "Report", style: .default) { _ in
            let vc = XGL_ReportReasonViewController()
            vc.id = self.liveId
            self.navigationController?.pushViewController(vc)
        }
        let action1 = UIAlertAction(title: "Quit", style: .default) { _ in
            self.navigationController?.popViewController()
        }

        let action2 = UIAlertAction(title: "Cancel", style: .cancel)
        actionController.addAction(action)
        actionController.addAction(action2)
        actionController.addAction(action1)
        self.present(actionController, animated: true)
    }
    
    @objc private func giftItemAction(){
        self.selectGiftItem()
    }
}

extension XGL_LiveRoomViewController{
    func selectGiftItem(){
        if self.chatInputView.inputTextView.isFirstResponder{
            self.chatInputView.inputTextView.resignFirstResponder()
        }
        self.view.addSubview(self.giftPickerView)
        self.giftPickerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.giftPickerView.showGiftPickerView { selectGift in
            self.sendGiftRequest(giftData: selectGift)
        }
    }
}

extension XGL_LiveRoomViewController{
    private func getUserDataRequest(){
        guard let userId = self.liveData?.userId else { return }
        PanRequestManager<XGL_RequestBaseResponse<UserFollowAndFansNumData>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .UserFollowsAndFansNum(userId: userId.description))) { result in
            switch result{
            case .success(let response):
                if let data = response.resultData {
                    self.inforView.userNameText.text = data.nickname
                }
                break
            default:
                break
            }
        }
    }
    
    private func getGiftDatasRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<GiftData>>,XGL_CustomRequestError>().request(CustomRequestAPI(requestAPI: .Gifts)) { result in
            switch result{
            case .success(let response):
                if let data = response.resultData {
                    self.giftPickerView.giftSource = data.data
                }
                break
            default:
                break
            }
        }
    }
    
    func commentRequest(id: String,content: String){
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        let data = PublishParamsData(data1: "4",pid: id,data8: content)
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .PublishData(data: data))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                self.getCommentDatasRequest()
                break
            default:
                break
            }
        }
    }
    
    private func getCommentDatasRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<PublishCommentData>>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .GetPublishData(userId: nil, page: 1, size: 500, data1: "4", pid: self.liveId, data5: nil))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let model = response.resultData{
                    self.chatView.chatDatas = model.data.reversed()
                    self.chatView.tableView.reloadData()
                }
                break
            default:
                break
            }
        }
    }
    
    private func getIsFollowRequest(){
        guard let userId = self.liveData?.userId else { return }
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .IsFollowUser(userId: userId.description))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let followResult = NSInteger(response.resultJson){
                    self.inforView.followItem.isSelected = followResult == 1
                }
                break
            default:
                break
            }
        }
    }
    
    func sendGiftRequest(giftData: GiftData){
        guard let userId = self.liveData?.userId else { return }
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<SendGiftResult>,XGL_CustomRequestError>().request(CustomRequestAPI(requestAPI: .SendGift(giftId: giftData.id, userId: userId.description))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let data = response.resultData {
                    self.giftPickerView.coin = data.amount
                    if data.enough == 0{
                        MXProgressHUD.hudWithText("Gift failure")
                    }else if data.enough == 2{
                        MXProgressHUD.hudWithText("Your balance is insufficient, please top it up")
                    }
                    if data.enough > 0{
                        self.animationView.showGiftAnimation(message: "\(self.inforView.userNameText.text) received a gift from \(XGL_userDataManager.share.userName)", giftData: giftData)
                    }
                }
                break
            default:
                break
            }
        }
    }
}

extension XGL_LiveRoomViewController: ChatInputDelegate{
    func sendChatMessage(content: String) {
        self.chatInputView.restoreInitialization()
        self.commentRequest(id: self.liveId, content: content)
    }
}

extension XGL_LiveRoomViewController{
    private func createXglView(){
        self.liveCoverView = UIImageView().then({ make in
            make.contentMode = .scaleAspectFit
        })
        self.chatView = XGL_LiveRoomChatView()
        self.chatInputView = XGL_LiveRoomChatInputView().then({ make in
            make.delegate = self
        })
        let giftItem = UIButton().then { make in
            make.setImage(imageWithName("img_xgl_live_gift_send"), for: .normal)
            make.addTarget(self, action: #selector(self.giftItemAction), for: .touchUpInside)
        }
        self.view.addSubviews([self.liveCoverView,self.chatView,self.chatInputView,self.animationView,giftItem])
        self.liveCoverView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.chatView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.bottom.equalTo(self.chatInputView.snp.top)
            make.width.equalToSuperview().multipliedBy(0.6)
        }
        self.chatInputView.snp.makeConstraints { make in
            make.bottom.centerX.width.equalToSuperview()
        }
        self.animationView.snp.makeConstraints { make in
            make.centerX.width.equalToSuperview()
            make.height.equalTo(50.0)
            make.top.equalTo(PanNavibarH + 5.0)
        }
        giftItem.snp.makeConstraints { make in
            make.right.equalTo(-15.0)
            make.bottom.equalTo(-BottomHeight - 70.0)
            make.width.height.equalTo(36.0)
        }
    }
    
    func creatClearNavigationBar(title: String) {
        self.navigationController?.navigationBar.barStyle = .default
        setNeedsStatusBarAppearanceUpdate()
        let backColor = UIColor.clear
       
        let navView = UIView().then { make in
            make.backgroundColor = backColor
        }
        let rightItem = UIButton().then { make in
            make.setImage(imageWithName("icon_more_white"), for: .normal)
            make.addTarget(self, action: #selector(self.moreItemAction), for: .touchUpInside)
        }
        inforView = XGL_LiveRoomUserItemView().then { make in
            make.isSelf = false
        }

        navView.addSubview(rightItem)
        navView.addSubview(inforView)
        self.view.addSubview(navView)

        inforView.snp.makeConstraints { make in
            make.bottom.equalTo(-6.0)
            make.left.equalTo(15.0)
        }
        rightItem.snp.makeConstraints { make in
            make.centerY.equalTo(inforView)
            make.right.equalTo(-12.0)
            make.height.equalTo(40.0)
            make.width.equalTo(40.0)
        }
        navView.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(PanNavibarH)
        }
    }
}
